package com.yao.club.service.impl;

import com.netease.yidun.sdk.core.utils.StringUtils;
import com.yao.club.entity.dto.Message;
import com.yao.club.entity.dto.SysImg;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.UserFollowRecord;
import com.yao.club.entity.result.ResultEntity;
import com.yao.club.entity.vo.UserProfileVO;
import com.yao.club.mapper.UserFollowMapper;
import com.yao.club.mapper.UserMapper;
import com.yao.club.reposittory.MessageRepository;
import com.yao.club.reposittory.SysImageRepository;
import com.yao.club.reposittory.UserFollowRecordRepository;
import com.yao.club.service.FriendsService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

@Service
public class FriendsServiceImpl implements FriendsService {
    @Resource
    UserMapper userMapper;

    @Autowired
    UserFollowRecordRepository userFollowRepository;

    @Autowired
    SysImageRepository sysImageRepository;
    @Resource
    UserFollowMapper userFollowMapper;

    @Autowired
    private MessageRepository messageRepository;

    /**
     * 关注和取消关注
     * @param memberId
     * @param username
     * @return
     */
    @Override
    public ResponseEntity<Boolean> follow(String memberId, String username) {

        UserEntity user = userMapper.select(username);
        UserFollowRecord userFollow1 = userFollowRepository.selectById( user.getMember_id()+"",memberId); //关注
        UserFollowRecord userFollow2 = userFollowRepository.selectById( memberId,user.getMember_id()+"");//被关注
        if (userFollow1 != null) {
            //取消关注
            userFollowRepository.delete(userFollow1);
            userMapper.unIncrementFollowCount(user.getMember_id()+"");
            userMapper.unIncrementFansCount(memberId);
            if (userFollow2 != null) {
                userMapper.unIncrementFriendsCount(memberId);
                userMapper.unIncrementFriendsCount(user.getMember_id()+"");
            }
            // 插入消息记录
            Message message = new Message();
            message.setModule(6); // 模块编号，例如 6 表示动态模块
            message.setTitle("粉丝消息");
            message.setContent("[{\\\"text\\\":\\\"掉粉了\\\"},{\\\"color\\\":\\\"red\\\",\\\"text\\\":\\\""+user.getNickname()+"\\\"},{\\\"text\\\":\\\"取消关注了您。\\\"}]");
            message.setMemberId(memberId); // 被关注者的 ID
            message.setIfRead(0); // 未读状态
            message.setCreateTime(Instant.now());
            message.setParam("{\\\"memberId\\\":"+user.getMember_id()+"}");
            return ResponseUtils.success(true);
        } else {
            //关注
            UserFollowRecord userFollow = new UserFollowRecord();
            userFollow.setFollowerId(user.getMember_id());
            userFollow.setFollowedId(Long.parseLong(memberId));
            userFollowRepository.save(userFollow);
            userMapper.incrementFollowCount(user.getMember_id()+"");
            userMapper.incrementFansCount(memberId);
            if (userFollow2 != null) {
                userMapper.incrementFriendsCount(memberId);
                userMapper.incrementFriendsCount(user.getMember_id()+"");
            }
            // 关注成功
            // 插入消息记录
            Message message = new Message();
            message.setModule(6); // 模块编号，例如 6 表示动态模块
            message.setTitle("粉丝消息");
            message.setContent("[{\\\"text\\\":\\\"有新粉丝\\\"},{\\\"color\\\":\\\"red\\\",\\\"text\\\":\\\""+user.getNickname()+"\\\"},{\\\"text\\\":\\\"关注了您，快去看看粉丝的主页吧。\\\"}]");
            message.setMemberId(memberId); // 被关注者的 ID
            message.setIfRead(0); // 未读状态
            message.setCreateTime(Instant.now());
            message.setParam("{\\\"memberId\\\":"+user.getMessages()+"}");
            messageRepository.save(message);
            return ResponseUtils.success(true);
        }
    }

    /**
     * 根据关键字查询用户并显示用户关系
     * @param nickname
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseEntity<ResultEntity<UserProfileVO>> searchUsersByNickname(String nickname, Integer pageNum, Integer pageSize, String currentUsername) {
        ResultEntity result = new ResultEntity<UserProfileVO>();
        try {
            // 获取当前用户信息
            String currentUserId = null;
            if (StringUtils.isNotEmpty(currentUsername)) {
                UserEntity currentUser = userMapper.select(currentUsername);
                if (currentUser != null) {
                    currentUserId = String.valueOf(currentUser.getMember_id());
                }
            }

            // 搜索用户
            List<UserEntity> users = userMapper.selectByNickName(nickname);
            
            // 转换为VO并设置关系
            List<UserProfileVO> userVOs = new ArrayList<>();
            for (UserEntity user : users) {
                UserProfileVO vo = new UserProfileVO();
                // 设置基本信息
                BeanUtils.copyProperties(user, vo);
                SysImg sysImg = sysImageRepository.selectById(String.valueOf(user.avatar_id));
                vo.setHeadImg(sysImg);
                // 设置关系状态
                if (currentUserId != null && !currentUserId.equals(user.getMember_id())) {
                    vo.setRelation(checkUserRelation(currentUserId, user.getMember_id()+""));
                } else {
                    vo.setRelation(0); // 自己或未登录
                }
                
                userVOs.add(vo);
            }
            // 设置分页结果
            result.setRecords(userVOs);
            result.setTotal(userVOs.size());
            result.setSize(pageSize);
            result.setCurrent(pageNum);
            result.setPages((userVOs.size() + pageSize - 1) / pageSize); // 计算总页数
            
            return ResponseUtils.success(result);
        } catch (Exception e) {
            return ResponseUtils.failed("搜索用户失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户id获得用户信息
     * @param memberId
     * @param currentUsername
     * @return
     */
    @Override
    public ResponseEntity<UserProfileVO> getUserInfo(String memberId, String currentUsername) {
        try {
            // 获取目标用户信息
            UserEntity user = userMapper.getUserByMemberId(memberId);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }

            // 获取当前用户信息（如果已登录）
            String currentUserId = null;
            if (StringUtils.isNotEmpty(currentUsername)) {
                UserEntity currentUser = userMapper.select(currentUsername);
                if (currentUser != null) {
                    currentUserId = currentUser.getMember_id()+"";
                }
            }

            // 转换为VO
            UserProfileVO vo = new UserProfileVO();
            BeanUtils.copyProperties(user, vo);
            // 设置基本信息
            BeanUtils.copyProperties(user, vo);
            SysImg sysImg = sysImageRepository.selectById(String.valueOf(user.avatar_id));
            vo.setHeadImg(sysImg);

            // 设置关系状态
            if (currentUserId != null && !currentUserId.equals(user.getMember_id())) {
                vo.setRelation(checkUserRelation(currentUserId, user.getMember_id()+""));
            } else {
                vo.setRelation(0); // 自己或未登录
            }

            // 设置是否是自己
            vo.setSelf(currentUserId != null && currentUserId.equals(user.getMember_id()));

            return ResponseUtils.success(vo);

        } catch (Exception e) {
            return ResponseUtils.failed("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 检查用户关系
     * @param currentUserId 当前登录用户ID
     * @param authorId 帖子作者ID
     * @return 关系类型 (0:无关系 1:粉丝 2:已关注 3:相互关注)
     */
    private int checkUserRelation(String currentUserId, String authorId) {
        // 检查当前用户是否关注了作者
        boolean isFollowing = userFollowMapper.checkFollowStatus(currentUserId, authorId);

        // 检查作者是否关注了当前用户
        boolean isFollowed = userFollowMapper.checkFollowStatus(authorId, currentUserId);

        if (isFollowing && isFollowed) {
            return 3; // 相互关注
        } else if (isFollowing) {
            return 2; // 已关注
        } else if (isFollowed) {
            return 1; // 粉丝
        } else {
            return 0; // 无关系
        }
    }
}
